package com.hbmcc.heshenghuo.pager

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.view.animation.Interpolator
import androidx.core.view.isVisible
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.hbmcc.heshenghuo.IS_LOGIN
import com.hbmcc.heshenghuo.R
import com.hbmcc.heshenghuo.databinding.FloorMyFrgPagerItemBinding

/**
 * @author 支豪亮
 * @date 2021/11/16 10:23 上午
 * @des 我的频道 个人、家庭、集团翻页展示的楼层的Adapter
 */
class FloorMyFrgPagerAdapter(private var data: List<FloorMyFrgPagerItem>, val viewPager: ViewPager2, val listener: FloorMyFrgGideItemListener) :
    RecyclerView.Adapter<FloorMyFrgPagerViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FloorMyFrgPagerViewHolder =
        FloorMyFrgPagerViewHolder(FloorMyFrgPagerItemBinding.inflate(LayoutInflater.from(parent.context), parent, false))

    override fun onBindViewHolder(holder: FloorMyFrgPagerViewHolder, position: Int) {
        holder.dataBinding.pagerItem = data[position]
        holder.dataBinding.callback = listener
        holder.dataBinding.pageIndex = position
        data[position].root = holder.dataBinding.root
    }

    override fun getItemCount(): Int = 3

    fun updateData(list: List<FloorMyFrgPagerItem>) {
        val result = DiffUtil.calculateDiff(object : DiffUtil.Callback() {
            override fun getOldListSize(): Int = data.size

            override fun getNewListSize(): Int = list.size

            override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean = true

            override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean = data[oldItemPosition] == list[newItemPosition]
        })
        data = list //提高刷新效率
        result.dispatchUpdatesTo(this) //提高刷新效率

    }

    fun onUpdateIndex(pageIndex: Int, grideIndex: Int, view: View) {
        if (!IS_LOGIN) { //没有登录
            Log.e("onBindViewHolder", "请登录")
            return
        }
        if (data[pageIndex].gideIndex == -1) {
            Log.e("onBindViewHolder", "数据加载中请稍后")
            return
        }
        val item = data[pageIndex].item(grideIndex) ?: return

        if (item.list!!.size == 1) {
            if (data[pageIndex].gideIndex != grideIndex) flipV(pageIndex, grideIndex, true)
        } else {
            Log.e("onBindViewHolder", "翻转操作")
            flipit(pageIndex, grideIndex, view, true)
            item.isStop = true
        }

    }

    fun updateFlip(pageIndex: Int) {
        if (!IS_LOGIN) return
        if (data[pageIndex].list.isNullOrEmpty()) return
        if (data[pageIndex].gideIndex == -1) return
        for (index in data[pageIndex].list!!.indices) {
            val list = data[pageIndex].item(index)?.list ?: continue
            if (data[pageIndex].item(index)!!.isStop) continue
            if (list.size < 2) continue
            val view = initView(pageIndex, index) ?: continue
            flipit(pageIndex, index, view, false)
        }
    }

    fun isStop(): Boolean {
        for (pageIndex in data.indices) {
            if (isFlipItem(pageIndex)) return false
        }
        return true
    }

    fun isFlipItem(pageIndex: Int): Boolean {
        if (!IS_LOGIN) return false
        if (data[pageIndex].list.isNullOrEmpty()) return false
        if (data[pageIndex].gideIndex == -1) return false

        for (index in data[pageIndex].list!!.indices) {
            val list = data[pageIndex].item(index)?.list ?: continue
            if (data[pageIndex].item(index)!!.isStop) continue
            if (list.size < 2) continue
            initView(pageIndex, index) ?: continue
            return true
        }
        return false
    }

    private fun initView(pageIndex: Int, grideIndex: Int): View? {
        return when (grideIndex) {
            0 -> data[pageIndex].root?.findViewById(R.id.include_my_frg_gride_item_one)
            1 -> data[pageIndex].root?.findViewById(R.id.include_my_frg_gride_item_one)
            2 -> data[pageIndex].root?.findViewById(R.id.include_my_frg_gride_item_one)
            3 -> {
                val view = data[pageIndex].root?.findViewById<View>(R.id.include_my_frg_gride_item_one)
                if (view?.isVisible == true) view else null
            }
            else -> null
        }
    }

    private fun flipit(pageIndex: Int, grideIndex: Int, view: View, isGide: Boolean) {
        val flipIndex = data[pageIndex].list!![grideIndex].flipIndex
        val visToInvis = ObjectAnimator.ofFloat(view, "rotationY", 0f, 90f)
        visToInvis.duration = 500
        visToInvis.interpolator = accelerator
        val invisToVis = ObjectAnimator.ofFloat(view, "rotationY", -90f, 0f)
        invisToVis.duration = 500
        invisToVis.interpolator = decelerator
        visToInvis.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(anim: Animator) {
                invisToVis.start()
                data[pageIndex].list!![grideIndex].flipIndex = if (flipIndex == 0) 1 else 0
                if (isGide) data[pageIndex].gideIndex = grideIndex
                notifyItemChanged(pageIndex)
            }
        })

        visToInvis.start()
        if (isGide || data[pageIndex].gideIndex == grideIndex) flipV(pageIndex, grideIndex, false)
    }

    private fun flipV(pageIndex: Int, grideIndex: Int, isUpdate: Boolean) {

        val view: View = data[viewPager.currentItem].root?.findViewById(R.id.inc_trip) ?: return
        val visToInvis = ObjectAnimator.ofFloat(view, "rotationX", 0f, -90f)
        visToInvis.duration = 500
        visToInvis.interpolator = accelerator
        val invisToVis = ObjectAnimator.ofFloat(view, "rotationX", 90f, 0f)
        invisToVis.duration = 500
        invisToVis.interpolator = decelerator
        visToInvis.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(anim: Animator) {
                invisToVis.start()
                if (isUpdate) {
                    notifyItemChanged(pageIndex)
                    data[pageIndex].gideIndex = grideIndex
                    notifyItemChanged(pageIndex)
                }
            }
        })
        visToInvis.start()
    }

    companion object {
        val accelerator: Interpolator = AccelerateInterpolator()
        val decelerator: Interpolator = DecelerateInterpolator()
    }


}

/**
 * FloorMyFrgPagerAdapter 的ViewHolder
 */
open class FloorMyFrgPagerViewHolder(var dataBinding: FloorMyFrgPagerItemBinding) : RecyclerView.ViewHolder(dataBinding.root)

/**
 * 当Item点击的操作
 */
interface FloorMyFrgGideItemListener {
    fun onUpdateIndex(pageIndex: Int, grideIndex: Int, view: View)
}